package com.wxmblog.photo.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wxmblog.base.common.utils.TokenUtils;
import com.wxmblog.photo.entity.ProductEntity;
import com.wxmblog.photo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxmblog.photo.dao.DownloadRecordDao;
import com.wxmblog.photo.entity.DownloadRecordEntity;
import com.wxmblog.photo.service.DownloadRecordService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service("downloadRecordService")
public class DownloadRecordServiceImpl extends ServiceImpl<DownloadRecordDao, DownloadRecordEntity> implements DownloadRecordService {

    @Autowired
    ProductService productService;

    @Transactional
    @Override
    public void saveDownloadRecord(String fileName, Integer userId) {

        Wrapper<ProductEntity> productEntityWrapper = new QueryWrapper<ProductEntity>().lambda()
                .likeLeft(ProductEntity::getFile, fileName);
        List<ProductEntity> productEntityList = productService.getBaseMapper().selectList(productEntityWrapper);
        for (ProductEntity productEntity : productEntityList) {

            Wrapper<DownloadRecordEntity> downloadRecordEntityWrapper = new QueryWrapper<DownloadRecordEntity>().lambda()
                    .eq(DownloadRecordEntity::getProductId, productEntity.getId())
                    .eq(DownloadRecordEntity::getUserId, userId);
            this.remove(downloadRecordEntityWrapper);
            
            DownloadRecordEntity downloadRecordEntity = new DownloadRecordEntity();
            downloadRecordEntity.setUserId(userId);
            downloadRecordEntity.setProductId(productEntity.getId());
            save(downloadRecordEntity);
        }
    }
}
